<?php
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;

header("content-type:text/html;charset=utf-8");
require 'helper/helper.php';
require 'helper/Db.php';
require 'vendor/autoload.php';
require 'config/mail.php';

error_reporting(E_ERROR);
//获取数据
$jsonData = file_get_contents('php://input');
$data = json_decode($jsonData, true);
$user_name = htmlentities($data['user_name']);
$email = htmlentities($data['email']);
$password = htmlentities($data['password']);
$password = rsaDecrypt($password);

//验证格式
if(empty($user_name) || empty($email) || empty($password)) {
    jsonReturn(['code' => 1, 'msg' => '参数不全']);
}
if (strlen(trim($user_name)) < 1) {
    jsonReturn(['code' => 1, 'msg' => '用户名不能为空']);
}
$pattern = "/^\S+@\S+\.\S+$/";
if (!preg_match($pattern, $email)) {
    jsonReturn(['code' => 1, 'msg' => '邮箱格式不正确']);
}
if (strlen(trim($password)) < 6) {
    jsonReturn(['code' => 1, 'msg' => '密码不能为空且不能小于6位']);
}

//判断是否已注册 若已有并且已激活，则直接返回已注册信息 若已有且未激活，则将原来该email数据删除
$db = new Db();
$query = "select * from users where email = :email";
$result = $db->query1($query, [':email' => ['data' => $email]]);
if ($result) {
    if ($result[0]['enable'])
        jsonReturn(['code' => 1, 'msg' => '此email已经注册']);
    else {
        $query = "delete from users where email = :email";
        $db->execute($query, [':email' => $email]);
    }
}

//插入数据
$salt = getSalt();
$md5_pwd = md5($password . $salt);
$query = "insert into users(user_name, email, password, salt, enable) values(:user_name, :email, :password, :salt, 1)";
try {
    //插入注册信息
    $db->pdo->beginTransaction();
    $inserted = $db->execute($query, [':user_name' => $user_name, ':email' => $email, ':password' => $md5_pwd, ':salt' => $salt]);
    if (!$inserted) {
        $db->pdo->rollBack();
        jsonReturn(['code' => 1, 'msg' => '数据库操作失败']);
    }

    //发送邮件
    $mailConfig = include 'config/mail.php';
    $mail = new PHPMailer(true);
    $mail->SMTPDebug = 0; // 启用详细调试输出
    $mail->isSMTP(); // 启用 SMTP
    $mail->Host = $mailConfig['host']; // SMTP 服务器地址
    $mail->SMTPAuth = true; // 启用 SMTP 认证
    $mail->Username = $mailConfig['username']; // SMTP 用户名（通常是你的邮箱地址）
    $mail->Password = $mailConfig['password']; // SMTP 密码
//    $mail->SMTPSecure = 'ssl'; // 启用 TLS 加密，`ssl` 也可用
    $mail->Port = $mailConfig['port']; // SMTP 端口，通常是 587 或 465（对于 ssl）
    $mail->CharSet = $mailConfig['charSet'];
    $mail->setFrom($mailConfig['username'], $mailConfig['sender']); // 发件人邮箱和名称
    $mail->addAddress($email, $user_name); // 收件人邮箱和名称

    //如果有验证码，删除
    $query = "delete from captchas where email = :email";
    $db->execute($query, [':email' => $email]);

    //验证码
    $captcha = mt_rand(100000, 999999);
    $query = "insert into captchas(email, captcha) values(:email, :captcha)";
    $db->execute($query, [':email' => $email, ':captcha' => $captcha]);
    $mail->Subject = '验证码';
    $mail->Body    = '您的注册验证码是：' . $captcha . ', 5分钟有效';

    // 发送邮件
    $mail->send();
} catch (Exception $e) {
    $db->pdo->rollBack();
    jsonReturn(['code' => 1, 'msg' => '注册失败']);
} finally {
    $db->pdo->commit();
}
jsonReturn(['code' => 0, 'msg' => '注册成功, 验证码已发送']);